package service

import (
	"errors"
	"gitee.com/ling1314/origin-utility/db"
	"gitee.com/ling1314/origin-utility/model"
	"gitee.com/ling1314/origin-utility/modules/repository"
	"gitee.com/ling1314/origin-utility/utils"
)

type clusterService struct {
	baseService
}

func (ser clusterService) Add(form model.ClusterForm, self *utils.CustomClaims) error {
	m := &model.Cluster{
		ClusterId:       utils.GetSoftId(),
		Name:            form.Name,
		CpuThreshold:    form.CpuThreshold,
		MemoryThreshold: form.MemoryThreshold,
		TimeOutAction:   form.TimeOutAction,
		MaxSessionTime:  form.MaxSessionTime,
		MaxTimeOutTime:  form.MaxTimeOutTime,
		ClusterType:     form.ClusterType,
		Creator:         self.Nickname,
		CreatorId:       self.UserID,
	}
	return repository.ClusterRepository.Insert(m)
}

func (ser clusterService) Update(form model.ClusterForm) error {
	var (
		clu model.Cluster
		err error
	)
	if clu, err = repository.ClusterRepository.FindById(form.ClusterId); err != nil {
		return err
	}
	clu.Name = form.Name
	clu.CpuThreshold = form.CpuThreshold
	clu.MemoryThreshold = form.MemoryThreshold
	clu.TimeOutAction = form.TimeOutAction
	clu.MaxSessionTime = form.MaxSessionTime
	clu.MaxTimeOutTime = form.MaxTimeOutTime
	clu.ClusterType = form.ClusterType
	return repository.ClusterRepository.Update(&clu)
}

func (ser clusterService) FindAll(self *utils.CustomClaims) (li []model.Cluster, err error) {
	if self.AccountLv == model.AccountLvForRoot {
		if li, err = repository.ClusterRepository.FindAll(); err != nil {
			return nil, err
		}
	} else {
		if li, err = repository.ClusterRepository.FindAllWithCreatorId(self.UserID); err != nil {
			return nil, err
		}
	}
	for i := range li {
		var hosts []model.AppHost
		if hosts, err = repository.HostRepository.FindWithClusterId(li[i].ClusterId); err != nil {
			return nil, err
		}
		if len(hosts) == 0 {
			hosts = make([]model.AppHost, 0)
		}
		li[i].Hosts = hosts
		var apps []model.AppIssue
		if apps, err = repository.AppRepository.FindListWithClusterId(li[i].ClusterId); err != nil {
			return nil, err
		}
		if len(apps) == 0 {
			apps = make([]model.AppIssue, 0)
		}
		li[i].Apps = apps
	}
	return li, nil
}

func (ser clusterService) Delete(id int64, self *utils.CustomClaims) error {
	var (
		err error
		clu model.Cluster
	)
	if clu, err = repository.ClusterRepository.FindById(id); err != nil {
		return err
	}
	if clu.CreatorId != self.UserID {
		return errors.New("只允许删除由自己创建的账户")
	}
	return repository.ClusterRepository.DeleteById(id)
}

func (ser clusterService) MoveHost(form model.MoveHostForm) error {
	var (
		err error
	)
	tx := db.GetDB().Begin()
	if err = repository.HostRepository.ReturnHost(form.ClusterId); err != nil {
		return err
	}
	if err = repository.HostRepository.UpdateClusterId(form.HostIds, form.ClusterId); err != nil {
		return err
	}
	return tx.Commit().Error
}
